<?php

namespace App\Orchid\Screens\Setting;

use App\Models\Setting;
use Illuminate\Http\Request;
use Orchid\Screen\Screen;
use Orchid\Screen\Fields\Input;
use Orchid\Screen\Fields\TextArea;
use Orchid\Screen\Fields\Select;
use Orchid\Screen\Fields\CheckBox;
use Orchid\Screen\Actions\Button;
use Orchid\Support\Facades\Toast;
use Orchid\Support\Facades\Layout;

class SettingEditScreen extends Screen
{
    /**
     * @var Setting
     */
    public $setting;

    /**
     * Fetch data to be displayed on the screen.
     *
     * @param Setting $setting
     *
     * @return array
     */
    public function query(Setting $setting): iterable
    {
        return [
            'setting' => $setting,
        ];
    }

    /**
     * The name of the screen displayed in the header.
     */
    public function name(): ?string
    {
        return $this->setting->exists ? '编辑设置' : '新建设置';
    }

    /**
     * Display header description.
     */
    public function description(): ?string
    {
        return $this->setting->exists ? '编辑系统设置项' : '创建新的系统设置项';
    }

    /**
     * The screen's action buttons.
     *
     * @return \Orchid\Screen\Action[]
     */
    public function commandBar(): iterable
    {
        return [
            Button::make('保存')
                ->icon('check')
                ->method('save'),

            Button::make('删除')
                ->icon('trash')
                ->method('remove')
                ->canSee($this->setting->exists)
                ->confirm('确定要删除这个设置吗？'),
        ];
    }

    /**
     * The screen's layout elements.
     *
     * @return \Orchid\Screen\Layout[]
     */
    public function layout(): iterable
    {
        return [
            Layout::tabs([
                '基本信息' => Layout::rows([
                    Input::make('setting.key')
                        ->title('设置键')
                        ->placeholder('输入设置键（如：site_name）')
                        ->required()
                        ->readonly($this->setting->exists)
                        ->help('设置的唯一标识符，创建后不可修改'),

                    Input::make('setting.name')
                        ->title('设置名称')
                        ->placeholder('输入设置显示名称')
                        ->required()
                        ->help('设置的显示名称'),

                    Select::make('setting.type')
                        ->title('设置类型')
                        ->options([
                            'text' => '文本',
                            'textarea' => '多行文本',
                            'number' => '数字',
                            'boolean' => '布尔值',
                            'select' => '选择',
                            'json' => 'JSON',
                        ])
                        ->value('text')
                        ->help('设置值的数据类型'),

                    Input::make('setting.group')
                        ->title('设置分组')
                        ->placeholder('输入设置分组（如：general, email）')
                        ->help('用于组织设置项的分组名称'),
                ]),
                
                '设置值' => Layout::rows([
                    Input::make('setting.value')
                        ->title('设置值')
                        ->placeholder('输入设置值')
                        ->canSee(fn() => in_array($this->setting->type ?? 'text', ['text', 'number']))
                        ->help('设置的具体值'),

                    TextArea::make('setting.value')
                        ->title('设置值')
                        ->placeholder('输入设置值')
                        ->rows(5)
                        ->canSee(fn() => in_array($this->setting->type ?? 'text', ['textarea', 'json']))
                        ->help('设置的具体值'),

                    CheckBox::make('setting.boolean_value')
                        ->title('启用')
                        ->sendTrueOrFalse()
                        ->canSee(fn() => ($this->setting->type ?? 'text') === 'boolean')
                        ->help('布尔类型设置的值'),

                    TextArea::make('setting.description')
                        ->title('设置描述')
                        ->placeholder('输入设置的详细描述')
                        ->rows(3)
                        ->help('设置项的详细说明'),
                ]),
                
                '高级选项' => Layout::rows([
                    Input::make('setting.options')
                        ->title('选项配置')
                        ->placeholder('JSON格式的选项配置')
                        ->help('对于select类型，配置可选项（JSON格式）'),

                    CheckBox::make('setting.is_public')
                        ->title('公开设置')
                        ->sendTrueOrFalse()
                        ->help('是否允许前端访问此设置'),

                    Input::make('setting.sort_order')
                        ->title('排序')
                        ->type('number')
                        ->value(0)
                        ->help('设置项的显示顺序'),
                ]),
            ]),
        ];
    }

    /**
     * Save setting
     *
     * @param Request $request
     * @param Setting $setting
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function save(Request $request, Setting $setting)
    {
        $request->validate([
            'setting.key' => 'required|string|max:255|unique:settings,key,' . $setting->id,
            'setting.name' => 'required|string|max:255',
            'setting.type' => 'required|in:text,textarea,number,boolean,select,json',
            'setting.value' => 'nullable|string',
            'setting.group' => 'nullable|string|max:255',
            'setting.description' => 'nullable|string',
            'setting.options' => 'nullable|string',
            'setting.sort_order' => 'nullable|integer',
        ]);

        $data = $request->get('setting');
        
        // 处理布尔类型的值
        if (($data['type'] ?? 'text') === 'boolean') {
            $data['value'] = $request->get('setting.boolean_value') ? '1' : '0';
        }
        
        // 验证JSON格式
        if (in_array($data['type'] ?? 'text', ['json', 'select']) && !empty($data['options'])) {
            $decoded = json_decode($data['options'], true);
            if (json_last_error() !== JSON_ERROR_NONE) {
                Toast::error('选项配置必须是有效的JSON格式');
                return back()->withInput();
            }
        }
        
        // 设置默认值
        $data['is_public'] = $request->get('setting.is_public', false);
        $data['sort_order'] = $data['sort_order'] ?? 0;

        $setting->fill($data)->save();

        Toast::info('设置已保存');

        return redirect()->route('platform.settings');
    }

    /**
     * Remove setting
     *
     * @param Setting $setting
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function remove(Setting $setting)
    {
        $setting->delete();

        Toast::info('设置已删除');

        return redirect()->route('platform.settings');
    }
}